package com.cbz.example.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cbz.example.entity.Order;
import com.cbz.example.entity.User;
import com.cbz.example.entity.vo.OrderVO;
import com.cbz.example.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    // 创建订单
    @PostMapping
    public boolean createOrder(@RequestBody Order order) {
        return orderService.save(order);
    }

    // 根据 ID 查询订单
    @GetMapping("/{id}")
    public OrderVO getOrderById(@PathVariable Long id) {
        // 拿到订单信息
        Order order = orderService.getById(id);
        // 通过其中的userId查询用户信息
        String url = "http://user-service/users/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        // 对结果进行封装
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setUser(user);
        return orderVO;
    }

    // 查询所有订单
    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.list();
    }

    // 分页查询订单
    @GetMapping("/page/{current}/{size}")
    public Page<Order> getOrdersByPage(@PathVariable long current, @PathVariable long size) {
        Page<Order> page = new Page<>(current, size);
        return orderService.page(page);
    }

    // 更新订单信息
    @PutMapping
    public boolean updateOrder(@RequestBody Order order) {
        return orderService.updateById(order);
    }

    // 根据 ID 删除订单
    @DeleteMapping("/{id}")
    public boolean deleteOrder(@PathVariable Long id) {
        return orderService.removeById(id);
    }
}